package com.ruoyi.app.controller;

import com.ruoyi.app.utils.RandomUtil;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单服务
 * @Author Alan Zhang
 * @Date 2025/3/15 13:21
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController extends BaseApiController{
    @Autowired
    private IJtOrderService jtOrderService;
    @Autowired
    private IJtUserAddressService jtUserAddressService;
    @Autowired
    private IJtProductService jtProductService;
    @Autowired
    private IJtCountryCodeService iJtCountryCodeService;
    @Autowired
    private IJtProductPublishService jtProductPublishService;
    @Autowired
    private IJtProductPublishSkuService jtProductPublishSkuService;
    @Autowired
    private IJtDistributorService jtDistributorService;

    @Autowired
    private IJtPaymentOrderService jtPaymentOrderService;
    @Autowired
    private IJtPaymentAccountService jtPaymentAccountService;

    //========== 提交订单 =========
    @PostMapping("/submit")
    public AjaxResult submit(@NotNull Long productId, @NotNull Long skuId, @NotNull Long qty, @NotNull Long addressId, String buyerRemark)
    {
        JtAppUser jtAppUser = getTokenAppUser();

        if(productId == null){
            return AjaxResult.error("产品id不能为空");
        }
        JtOrder jtOrder = new JtOrder();
        jtOrder.setOrderNo(RandomUtil.generateOrderNumber());
        jtOrder.setOrderStatus(0);//待付款
        jtOrder.setBuyer(jtAppUser.getUserName());
        jtOrder.setUserId(jtAppUser.getUserId());
        jtOrder.setOrderType(1);
        if(jtAppUser.getApplyStatus() !=null && 1 == jtAppUser.getApplyStatus()) {
            //分销商订订单
            JtDistributor distributorParam = new JtDistributor();
            distributorParam.setUserId(jtAppUser.getUserId());
            distributorParam.setAuditStatus(1);
            List<JtDistributor> distributorList = jtDistributorService.selectJtDistributorList(distributorParam);
            if (distributorList.size() > 0) {
                jtOrder.setOrderType(2); //分销订单
            }
        }
        //买家备注
        jtOrder.setBuyerRemark(buyerRemark);
        jtOrder.setBuyQty(qty);

        JtProductPublish productPublishDb = jtProductPublishService.selectJtProductPublishByProductId(productId);
        if(productPublishDb == null) {
            return AjaxResult.error("产品不存在！");
        }
        jtOrder.setCurrency(productPublishDb.getCurrency());

        JtUserAddress jtUserAddress = jtUserAddressService.selectJtUserAddressByAddressId(addressId);
        //用户地址
        jtOrder.setCountry(jtUserAddress.getCountry());
        jtOrder.setProvince(jtUserAddress.getProvince());
        jtOrder.setCity(jtUserAddress.getCity());
        jtOrder.setDistrict(jtUserAddress.getDistrict());
        jtOrder.setFullAddress(jtUserAddress.getFullAddress());
        jtOrder.setReceiver(jtUserAddress.getReceiver());
        jtOrder.setPhoneNumber(jtUserAddress.getPhoneNumber());
        jtOrder.setZipCode(jtUserAddress.getZipCode());

        JtProductPublishSku jtProductPublishSku = jtProductPublishSkuService.selectJtProductPublishSkuBySkuId(skuId);
        //订单明细
        List<JtOrderItem> jtOrderItemList = new ArrayList<>();
        JtOrderItem jtOrderItem = new JtOrderItem();
        jtOrderItem.setSalePrice(jtProductPublishSku.getSalePrice());
        jtOrderItem.setProdCount(qty);

        BigDecimal totalAmount = new BigDecimal(qty).multiply(jtProductPublishSku.getSalePrice());
        jtOrderItem.setTotalAmount(totalAmount);
        jtOrderItem.setProductId(productId);
        jtOrderItem.setProdName(productPublishDb.getProductTitle());
        jtOrderItem.setSkuId(skuId);
        jtOrderItem.setImageUrl(jtProductPublishSku.getImageUrl());
        jtOrderItem.setSkuName(jtProductPublishSku.getSkuName());
        jtOrderItem.setStyleNo(productPublishDb.getStyleNo());
        jtOrderItem.setSkuCode(jtProductPublishSku.getSkuCode());
        jtOrderItemList.add(jtOrderItem);
        jtOrder.setJtOrderItemList(jtOrderItemList);
        jtOrder.setOrderAmount(totalAmount);
        jtOrder.setCreateBy(jtAppUser.getUserName());
        jtOrderService.insertJtOrder(jtOrder);
        //订单信息
        return AjaxResult.success(jtOrder);
    }

    //========== 取消订单列表 =========
    @PostMapping("/cancel")
    public AjaxResult cancel(Long orderId)
    {
        JtOrder order = new JtOrder();
        order.setOrderId(orderId);
        order.setOrderStatus(3);//订单完成
        order.setCloseType(3);//买家取消
        order.setFinallyTime(DateUtils.getNowDate());
        order.setCancelTime(DateUtils.getNowDate());
        int rows = jtOrderService.updateJtOrder(order);
        if(rows > 0){
            return AjaxResult.success("order cancel success");
        } else {
            return AjaxResult.success("order cancel fail");
        }
    }

    //========== 购买列表 =========
    @PostMapping("/payment")
    public AjaxResult payment(Long orderId, Integer paymentMethod)
    {
        JtOrder jtOrderDb = jtOrderService.selectJtOrderByOrderId(orderId);
        if(jtOrderDb == null){
            return AjaxResult.error("订单不存在！");
        }
        if(jtOrderDb.getCloseType() != null){
            if(1 == jtOrderDb.getCloseType()){
                return AjaxResult.error("超时未支付！");
            } else if(2== jtOrderDb.getCloseType()){
                return AjaxResult.error("退款关闭！");
            } else if(3== jtOrderDb.getCloseType()){
                return AjaxResult.error("买家取消！");
            } else if(4== jtOrderDb.getCloseType()){
                return AjaxResult.error("已通过货到付款交易！");
            } else {
                return AjaxResult.error("未知状态！");
            }
        }
        if(jtOrderDb.getIsPayed() == 1){
            return AjaxResult.error("已支付！");
        }

        if(paymentMethod == null){
            return AjaxResult.error("请选择支付方式！");
        }

        JtAppUser jtAppUser = getTokenAppUser();

        JtPaymentOrder jtPaymentOrder = new JtPaymentOrder();
        jtPaymentOrder.setPaymentNo(RandomUtil.generatePaymentNumber());
        jtPaymentOrder.setBuyerUser(jtAppUser.getUserName());
        jtPaymentOrder.setOrderId(orderId);
        jtPaymentOrder.setCurrency(jtOrderDb.getCurrency());
        jtPaymentOrder.setPaymentMethod(paymentMethod);
        jtPaymentOrder.setPaymentAmount(jtOrderDb.getPaymentAmount());
        jtPaymentOrder.setUserId(jtAppUser.getUserId());
        int rows= jtPaymentOrderService.insertJtPaymentOrder(jtPaymentOrder);
        if(rows > 0) {
            return AjaxResult.success("payment success");
        } else {
            return AjaxResult.error();
        }
    }

    //========== 取消订单支付列表 =========
    @PostMapping("/payment/cancel")
    public AjaxResult paymentCancel(String paymentNo)
    {
        if(StringUtils.isEmpty(paymentNo)){
            return AjaxResult.error("支付单号不能为空！");
        }
        JtAppUser jtAppUser = getTokenAppUser();
        JtPaymentOrder paymentOrder = jtPaymentOrderService.selectJtPaymentOrderByPaymentNo(paymentNo);
        if(paymentOrder.getUserId().equals(jtAppUser.getUserId())){
            if(paymentOrder.getPaymentStatus() == 0){
                paymentOrder.setCloseTime(DateUtils.getNowDate());
                paymentOrder.setPaymentStatus(2);
                int rows = jtPaymentOrderService.updateJtPaymentOrder(paymentOrder);
                if(rows > 0) {
                    return AjaxResult.success("payment cancel success");
                } else {
                    return AjaxResult.error("payment cancel fail");
                }
            } else {
                return AjaxResult.error("payment status:" + paymentOrder.getPaymentStatus());
            }
        } else {
            return AjaxResult.error("订单与用户不一致！");
        }
    }


    //========== 支付账号列表 =========
    @PostMapping("/payment/account")
    public AjaxResult paymentAccount()
    {
        JtAppUser jtAppUser = getTokenAppUser();
        jtAppUser.getCountryCode();
        JtPaymentAccount param = new JtPaymentAccount();
        param.setStatus(0);
        List<JtPaymentAccount> paymentAccountList = jtPaymentAccountService.selectJtPaymentAccountList(param);
        return AjaxResult.success("success", paymentAccountList);
    }
}
